const Controller = require('egg').Controller;

class AccountController extends Controller {
  async accountLogin() {
    const { ctx } = this;
    ctx.validate({
      account_name: { type: 'string' },
      password: { type: 'string' },
    });
    const param = ctx.request.body;
    const { data: account, error } = await ctx.service.account.accountLogin(param);
    const resBody = {
      code: 200,
      msg: 'Login success',
    };
    if (error) {
      resBody.code = -1;
      resBody.msg = '帐号或密码错误';
      ctx.body = resBody;
      return;
    }

    // 生成token
    const { secret, expiresIn } = this.config.jwt;
    resBody.data = { account }
    resBody.data.token = this.app.jwt.sign({ id: account.account_id }, secret, {
      expiresIn,
    });
    resBody.data.resource_prefix = ctx.helper.resourcePrefix;
    ctx.body = resBody;
  }

  async getAccountById() {
    const { ctx } = this;
    const param = ctx.request.body;
    const { data: info } = await ctx.service.account.getAccountById(
      param.account_id,
    );
    ctx.body = {
      code: 200,
      msg: 'Get Account success',
      data: info,
    };
  }

  async updatePassword() {
    const { ctx } = this;
    ctx.validate({
      account_id: { type: 'number' },
      new_password: { type: 'string' },
      old_password: { type: 'string' },
    });
    const param = ctx.request.body;
    const { error } = await ctx.service.account.updatePassword(param);
    const response = {
      code: 200,
      msg: 'Update password success',
    };
    if (error) {
      response.code = -1;
      response.msg = error;
    }
    ctx.body = response;
  }
}

module.exports = AccountController;
